package core.util;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.util.concurrent.atomic.AtomicInteger;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class Utilities
{
    public static final String COOKIE_NAME = "CS5300SESSION";

    /**
     * Create a unique session id based on the following parameters
     * 
     * @param req
     *            http request object
     * @param servletAddr
     *            information of the processing servlet
     * @param serverStartTime
     *            start time of the servlet
     * @param uniqueCounter
     *            this is the nth new session
     * @return unique session id in String
     * @throws UnsupportedEncodingException
     * @throws NoSuchAlgorithmException
     */
    public static String generateUniqueSessionId( HttpServletRequest req,
            String servletAddr, long serverStartTime,
            AtomicInteger uniqueCounter ) throws UnsupportedEncodingException,
            NoSuchAlgorithmException {
        // increment the counter
        uniqueCounter.incrementAndGet();

        // construct the unique session id
        String sessionId = servletAddr + serverStartTime + req.getRemoteAddr()
                + req.getRemotePort() + uniqueCounter.get();

        return sessionId;
    }

    public static void redirectPage( HttpServletResponse response,
            String pageName ) throws IOException {
        response.sendRedirect( response.encodeRedirectURL( pageName ) );
    }
}
